import requests
import time
import hashlib
import json

REQUEST_URL = 'http://openapi.youdao.com/api'
query_cache = dict()


def query_youdao(word: str)->list:
    """
    youdao词典查询
    """
    global query_cache
    if query_cache.get(word) is not None:
        return query_cache[word]
    conn = requests.session()
    pa = _youdao_params(word)
    response = conn.get(url=REQUEST_URL, params=pa)
    ret_list = _parse_resp(response.text)
    query_cache[word] = ret_list
    return ret_list


def _youdao_params(word):
    salt = str(int(time.time()))
    key = "np8qsfImwMhodl34Gzjb0KneMzmwxUCu"
    appKey = "775e8a018708b7a9"
    # key = "LZFy0Ys97fCnWnb6f439ZD4hj37lOz8c"
    # appKey = "0998295557105306"
    md5 = hashlib.md5()
    md5.update((appKey + word + salt + key).encode())
    sign = md5.hexdigest().upper()
    params = {
        'q': word,
        'from': 'auto',
        'to': 'auto',
        'appKey': appKey,
        'salt': salt,
        'sign': sign,
    }
    return params


def _parse_resp(text):
    ret_list = []
    resp_dict = json.loads(text)
    dict_list = resp_dict.get('web')
    if dict_list is not None or len(dict_list) > 0:
        for d in dict_list:
            ret_list.extend(d.get('value'))
    dict_list = resp_dict.get('translation')
    if dict_list is not None or len(dict_list) > 0:
        dict_list.extend(ret_list)
        return dict_list
    return ret_list


if __name__ == '__main__':
    print(query_youdao('fly'))
